// 封装请求头和拦截器
import axios from 'axios'
import store from '@/store'
import { reqRefreshToken } from '@/api/user'
import router from '@/router'

const instance = axios.create({
  baseURL: 'http://192.168.134.45:8000'
})

instance.interceptors.request.use(function (config) {
  const token = store.state.user.tokenInfo
  if (token && !config.headers.Authorization) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

instance.interceptors.response.use(function (response) {
  return response.data
}, async function (error) {
  const refreshToken = store.state.user.refreshToken
  if (error.response.status === 401) {
    // 刷新token=>重新发送请求request(error.config)
    try {
      if (refreshToken) {
        const res = await reqRefreshToken(refreshToken)
        store.commit('user/setTokenInfo', res.data.token)
        error.config.headers.Authorization = `Bearer ${res.data.token}`
        return instance.request(error.config)
      } else {
        store.commit('user/removeToken')
        router.push({
          path: '/login',
          query: {
            backto: router.currentRoute.fullPath
          }
        })
      }
    } catch (e) {
      store.commit('user/removeRefreshToken')
      store.commit('user/removeToken')
      router.push({
        path: '/login',
        query: {
          backto: router.currentRoute.fullPath
        }
      })
    }
  }
  return Promise.reject(error)
})

export default instance
